package com.example.ware.controller;

import com.example.ware.model.responseData.ResponseData;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/upload")
public class UploadController {


    /**
     *上传图片列表的接口
     */
    @PostMapping("/uploadImages")
    public ResponseData uploadImages(@RequestParam("images") List<MultipartFile> images) {
        System.out.println("55555555555555555555555555555555");
        System.out.println(images);
        List<String> fileNames = new ArrayList<>();
        for (MultipartFile image : images) {
            if (!image.isEmpty()) {
                String fileName = image.getOriginalFilename();
//                String path="E/img/";
                String path = "/root/ke/img/"; //阿里云
                try {
                    image.transferTo(new File(path+fileName));
                } catch (IOException e) {
                    return new ResponseData(-1, false,"上传失败", 200);
                }

                fileNames.add(fileName);
            }
        }
        return new ResponseData(fileNames,true,"上传成功",200);
    }
    //    上传文章的封面图片
//
    @PostMapping("image")
    private ResponseData uploadBanner(MultipartFile url){
        String fileName = url.getOriginalFilename();
//    String path = "E:/img/";
        String path = "/root/ke/img/"; //阿里云
        File file = new File(path); //3. 判断路径是否存在，不存在则新建
        if (!file.exists()){
            file.mkdir();
        }
        // 3.改名,避免重名,定义新文件的名字
         String newName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
        String message="图片上传失败";
        String realPath = "";//图片的真实地址
        try {
            url.transferTo(new File(path+newName));
            message= "上传成功";
            realPath= path + fileName;  // 获取图片在服务器的真实地址
        } catch (IOException e) {
            message=message+e.toString();
            return new ResponseData(-1, false, message, 200);
        }

        if (message!="图片上传失败")
            return new ResponseData(newName, true,  message+"记录增加成功", 200);
        else
            return new ResponseData(-1, false, "请求失败", 200);
    }










}
